using System;
using System.Collections.Generic;
using UnityEngine;

namespace Gameplay.PVE.Effect
{
    public class ChainEffect : MonoBehaviour
    {
        public List<ParticleSystem> particleSystems;

        private Transform start;
        private Transform end;

        private Vector3 startPosition;
        private Vector3 endPosition;

        public bool useLengthScale = false;
        private bool isActive = false;

        public void Play(Transform start, Transform end)
        {
            if (particleSystems == null)
            {
                return;
            }

            isActive = true;
            this.start = start;
            this.end = end;
            this.SetActive( false);
            UpdatePositionAndDirection();
            this.SetActive(true);
        }

        public void Stop()
        {
            isActive = false;
        }
        
        private void Update()
        {
            if (particleSystems == null)
            {
                return;
            }

            if (!isActive)
            {
                return;
            }
            UpdatePositionAndDirection();
        }

        private void UpdatePositionAndDirection()
        {
            if (start != null)
            {
                startPosition = start.position;
            }

            if (end != null)
            {
                endPosition = end.position;
            }
            var length = Vector3.Distance(startPosition, endPosition);
            var forward = endPosition - startPosition;
            for (int i = 0; i < particleSystems.Count; i++)
            {
                
                if (useLengthScale)
                {
                    var renderer = particleSystems[i].GetComponent<ParticleSystemRenderer>();
                    renderer.lengthScale = length;
                }
                else
                {
                    var particleSystemMain = particleSystems[i].main;
                    particleSystemMain.startSizeY = new ParticleSystem.MinMaxCurve(length / 2);
                }
                
            }
            transform.position = startPosition;
            transform.forward = forward;
        }
    }
}